import datetime
import hashlib
import json
from bson.objectid import ObjectId

import pymongo

#用户密码信息类
class MyMong(object):
    #初始化
    def __init__(self):
        self.db = pymongo.MongoClient('mongodb://127.0.0.1:27017')
        self.mydb = self.db['mydb']
        self.mycol = self.mydb['mycol']
    #根据名称查找密码
    def info(self, userid,id):
        info = self.mycol.find_one({'userid': userid,'id':id})
        if info is not None:
            return json.dumps({'data': {'code': 200, 'key': info['passwd']}})
        else:
            return json.dumps({'data': {'code': '201', 'key': '密码不存在'}})
    #根据userid查找所有密码
    def allInfo(self, userid):
        datas = self.mycol.find({'userid': userid})
        s = {
            'data': {
                'code': 200,
                'list': []
            }
        }
        k = s['data']['list']
        for ss in datas:
            item = {}
            item['name'] = ss['name']
            item['passwd'] = ss['passwd']
            item['time']=ss['time']
            item['id']=ss['id']
            
            k.append(item)
        return json.dumps(s)
    #添加密码
    def adds(self, name, passwd, userId):
        Time = datetime.datetime.now()
        newTime = str(Time)
        thisTime = newTime.split('.')
        ids = str(ObjectId())
        self.mycol.insert({'name': name, 'passwd': passwd,
                           'time': thisTime[0], 'userid': userId,'id':ids})
        return str(name)

#用户信息类
class userInsart(object):
    #初始化
    def __init__(self):
        self.db = pymongo.MongoClient('mongodb://127.0.0.1:27017')
        self.userdb = self.db['mydb']
        self.userinfo = self.userdb['userinfo']
    #存储方法
    def userinsart(self, userid, username,avatarUrl):
        Time = datetime.datetime.now()
        newTime = str(Time)
        thisTime = newTime.split('.')
        userids = userid
        usernames = username
        avatarUrl = avatarUrl
        get_userid = self.userinfo.find_one({'userid': userids})
        if get_userid is None:
            self.userinfo.insert(
                {'name': usernames, 'userid': userids, 'time': thisTime[0],'avatarUrl':avatarUrl})
            return "注册成功"
        else:
            return "已注册"

